const state = {
  token: localStorage.getItem('token') || '',
  userInfo: JSON.parse(localStorage.getItem('userInfo')) || null
}

const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
    localStorage.setItem('token', token)
  },
  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
  },
  CLEAR_AUTH(state) {
    state.token = ''
    state.userInfo = null
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }
}

const actions = {
  login({ commit, dispatch }, loginForm) {
    return new Promise((resolve, reject) => {
      // 模拟API调用添加基础验证
      if (!loginForm.username || !loginForm.password) {
        reject(new Error('用户名和密码不能为空'))
        return
      }
      const mockLogin = (loginForm) => {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            // 模拟API响应格式
            if (loginForm.username === 'admin' && loginForm.password === '123456') {
              resolve({
                code: 200,
                message: '登录成功',
                token: 'mock-token-' + Math.random().toString(36).substr(2),
                userInfo: {
                  username: 'admin',
                  nickname: '管理员',
                  avatar: 'https://example.com/avatar/default.png',
                  roles: ['admin']
                }
              })
              localStorage.setItem('admin', true);
              console.log("change_admin");
              // dispatch("changeSetting", {
              //   key: "admin",
              //   value: true
              // })
            } else if (loginForm.username === 'user' && loginForm.password === '123456') {
              resolve({
                code: 200,
                message: '登录成功',
                token: 'mock-token-' + Math.random().toString(36).substr(2),
                userInfo: {
                  username: 'user',
                  nickname: '普通用户',
                  avatar: 'https://example.com/avatar/default.png',
                  roles: ['user']
                }
              })
              localStorage.setItem('admin', false);
              console.log("change_admin");
              // dispatch("changeSetting", {
              //   key: "admin",
              //   value: false
              // })
            }
            else {
              reject({
                code: 401,
                message: '用户名或密码错误'
              })
            }
          }, 500) // 模拟网络延迟
        })
      }
      mockLogin(loginForm)
        .then(response => {
          if (response && response.token) {
            commit('SET_TOKEN', response.token)
            commit('SET_USER_INFO', response.userInfo)
            resolve(response) // 返回完整响应数据
          } else {
            reject(new Error('无效的响应数据'))
          }
        })
        .catch(error => {
          // 统一错误处理
          const errMsg = error.message || '登录失败，请检查用户名和密码'
          reject(new Error(errMsg))
        })
    })
  },

  logout({ commit }) {
    return new Promise((resolve) => {
      commit('CLEAR_AUTH')
      resolve()
    })
  },
  register({ commit }, formData) {
    return new Promise((resolve, reject) => {
      // 模拟注册API
      setTimeout(() => {
        if (formData.username && formData.password) {
          resolve({ message: '注册成功' })
        } else {
          reject(new Error('注册信息不完整'))
        }
      }, 500)
    })
  },

  resetPassword({ commit }, { email, captcha }) {
    return new Promise((resolve, reject) => {
      // 模拟密码重置API
      setTimeout(() => {
        if (email.includes('@') && captcha === '123456') {
          resolve({ message: '密码重置邮件已发送' })
        } else {
          reject(new Error('验证码错误或邮箱不存在'))
        }
      }, 500)
    })
  }
}

// 增强的模拟登录API
// function mockLogin(loginForm) {
//   return new Promise((resolve, reject) => {
//     setTimeout(() => {
//       // 模拟API响应格式
//       if (loginForm.username === 'admin' && loginForm.password === '123456') {
//         resolve({
//           code: 200,
//           message: '登录成功',
//           token: 'mock-token-' + Math.random().toString(36).substr(2),
//           userInfo: {
//             username: 'admin',
//             nickname: '管理员',
//             avatar: 'https://example.com/avatar/default.png',
//             roles: ['admin']
//           }
//         })
//         this.$store.dispatch("changeSetting", {
//           key: "admin",
//           value: true
//         })
//       } else if (loginForm.username === 'user' && loginForm.password === '123456') {
//         resolve({
//           code: 200,
//           message: '登录成功',
//           token: 'mock-token-' + Math.random().toString(36).substr(2),
//           userInfo: {
//             username: 'user',
//             nickname: '普通用户',
//             avatar: 'https://example.com/avatar/default.png',
//             roles: ['user']
//           }
//         })
//         this.$store.dispatch("changeSetting", {
//           key: "admin",
//           value: false
//         })
//       }
//       else {
//         reject({
//           code: 401,
//           message: '用户名或密码错误'
//         })
//       }
//     }, 500) // 模拟网络延迟
//   })
// }

const getters = {
  isAuthenticated: state => !!state.token,
  currentUser: state => state.userInfo
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}